package Test.proxy_cglib;

import net.sf.cglib.proxy.*;

import java.lang.reflect.Method;

/**
 * cglib 实现动态代理
 */
public class SecurityMethodInterceptor implements MethodInterceptor {

    /**
     *  需要被被代理的对象
     */
    private Object target;

    public SecurityMethodInterceptor(Object target) {
        this.target = target;
    }

    /**
     * @param o
     * @param method
     * @param args
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        before();
        Object invoke = method.invoke(this.target, args);
        after();
        return invoke;
    }

    //普通无参数对构造方法
   /* public Object getProxyInstance(){
        Enhancer enhancer = new Enhancer();//设置一个
        enhancer.setSuperclass(target.getClass());//设置父类类
        enhancer.setCallback(this);
        return enhancer.create();

    }*/


    public Object getProxyInstance(){
        Enhancer enhancer = new Enhancer();
        //传入父类的类型，和父类的类型 （也就是要生的代理的父类类型）
        CallbackHelper callbackHelper = new CallbackHelper(ExecuteClassImplements.class,new Class[0]) {
            @Override
            protected Object getCallback(Method method) {
                //指定一个特定的拦截规则继续 进行拦截 （这里拦截了 返回值是 String 类型的 方法）
                if(method.getDeclaringClass() != Object.class && method.getReturnType() == String.class){
                    return new FixedValue() {
                        @Override
                        public Object loadObject() throws Exception {
                            return "its not excepted value , because FixedValue was changed that";
                        }
                    };
                } else {
                    return NoOp.INSTANCE;//否则放行
                }
            }
        };
        enhancer.setSuperclass(ExecuteClassImplements.class);
        enhancer.setCallbackFilter(callbackHelper);
        enhancer.setCallbacks(callbackHelper.getCallbacks());
        return enhancer.create();
    }

    private void before() {
        System.out.println("前置增强");
    }

    private void after() {
        System.out.println("后置增强");
    }
}
